import {
  AccountLoginRequest,
  requestUserInfoById,
  requestUserMenusById
} from '@/service/login/login'
import { AccountLoginType } from '@/service/login/type'
import { Module } from 'vuex'
import { IRootState } from '../types'
import { ILoginState, IUserInfoResult, IUserMenusResult } from './types'
import LocalCache from '@/utils/cache'
import router from '@/router'
import { mapMenusToPermissions, mapMenusToRoutes } from '@/utils/map-menus'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: IUserInfoResult) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: IUserMenusResult) {
      state.userMenus = userMenus
      //过滤旧版本图标格式
      state.userMenus.forEach((element: IUserMenusResult) => {
        element.icon = element.icon!.replace('el-icon-', '')
        element.icon = element.icon.replaceAll('-', '')
      })
      //根据权限动态添加路由
      const routers = mapMenusToRoutes(state.userMenus)
      routers.forEach((route) => {
        router.addRoute('main', route)
      })
      //获取用户按钮的权限
      const permissions = mapMenusToPermissions(state.userMenus)
      state.permissions = permissions
    }
  },
  getters: {},
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: AccountLoginType) {
      //登陆
      const loginResult = await AccountLoginRequest(payload)
      const { id, token } = loginResult.data
      commit('changeToken', token)
      LocalCache.setCache('token', token)

      //发送初始化的请求（完整的role/department）
      dispatch('getInitialDataAction', null, { root: true })

      //用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('changeUserInfo', userInfo)
      LocalCache.setCache('userInfo', userInfo)

      //用户menus
      const userMenusResult = await requestUserMenusById(userInfo.role.id)
      const userMenus = userMenusResult.data
      commit('changeUserMenus', userMenus)
      LocalCache.setCache('userMenus', userMenus)

      router.push('/main')
    },
    loadLocalLogin({ commit, dispatch }) {
      const token = LocalCache.getCache('token')
      if (token) {
        commit('changeToken', token)
        //发送初始化的请求（完整的role/department）
        dispatch('getInitialDataAction', null, { root: true })
      }
      const userInfo = LocalCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = LocalCache.getCache('userMenus')
      if (token) {
        commit('changeUserMenus', userMenus)
      }
    }
  }
}

export default loginModule
